<?php
declare (strict_types = 1);
namespace app\admin\controller;

use think\Request;
use think\facade\{View};
use think\exception\ValidateException;

use app\common\model\{Product, ProductCate, Img, Sku, ProductSku};
use app\common\validate\{ProductValidate, ProductCateValidate, SkuValidate};

/** 产品管理 */
class ProductController extends BaseController
{
    private $productModel;
    public function __construct(Product $productModel)
    {
        parent::initialize();
        $this->productModel = $productModel;
    }

    /** 渲染产品分类列表页面 */
    public function product_cate_list()
    {
        return view();
    }

    /** 渲染产品分类添加页面 */
    public function product_cate_add()
    {
        return view();
    }

    /** 产品分类数据列表 */
    public function product_cate_data()
    {
        $data = input('get.');

        try{
            validate(ProductCateValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $where = [];

        /** 搜索条件 */
        if($data && isset($data['key'])){
            if(!empty($data['key']['name'])){
                $where[] = [['name', 'like', '%' . $data['key']['name'] . '%']];
            }
        }

        $productCateModel = new ProductCate();

        /** 查询数据总条数 */
        $count = $productCateModel->getNum($where)['data'];

        /** 查询列表 */
        $list = $productCateModel->getList($where, 1, $data['page'], $data['limit'], '*', 'id DESC');

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        $this->success_back('ok', $list['data'], $count);
    }

    /** 添加分类 */
    public function product_cate_add_data()
    {
        $data = input('');

        try{
            validate(ProductCateValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $productCateModel = new ProductCate();

        $flag = $productCateModel->add(['name' => $data['name']]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('添加成功');
    }

    /** 修改分类名称 */
    public function set_cate_name()
    {
        $data = input('');

        try{
            validate(ProductCateValidate::class)->scene('edit')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $productCateModel = new ProductCate();

        $flag = $productCateModel->edit(['id' => $data['id'], $data['field'] => $data['value']]);

        if($flag['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        $this->success_back('编辑成功');
    }

    /** 删除分类 */
    public function product_cate_del()
    {
        $data = input('');

        try{
            validate(ProductCateValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $productCateModel = new ProductCate();

        $flag = $productCateModel->del(['id' => $data['id']]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('删除成功');
    }





    /** 渲染产品列表页面 */
    public function product_list()
    {
        return view();
    }

    /** 渲染产品添加页面 */
    public function product_add()
    {
        $skuModel  = new Sku();
        $cateModel = new ProductCate();
        $cate_list = $cateModel->getList([], 0)['data'];
        $sku = $skuModel->getList([], 0)['data'];

        View::assign('cate_list', $cate_list);
        View::assign('sku', $sku);
        return view();
    }

    /** 渲染产品编辑页面 */
    public function product_edit()
    {
        $data = input('');
        $imgModel  = new Img();
        $skuModel  = new Sku();
        $cateModel = new ProductCate();
        $productSkuModel = new ProductSku();

        $info = $this->productModel->getFind(['id' => $data['id']])['data'];

        $info['banner_img'] = $imgModel->getList(['obj_type' => 1, 'obj_id' => $info['id'], 'obj_cate' => 1], 0)['data'];
        $info['sku'] = $productSkuModel->getCol(['product_id' => $info['id']], 'sku_id')['data'];

        $cate_list = $cateModel->getList([], 0)['data'];
        $sku = $skuModel->getList([], 0)['data'];

        View::assign('info', $info);
        View::assign('cate_list', $cate_list);
        View::assign('sku', $sku);
        return view();
    }

    /** 产品列表数据列表 */
    public function product_data()
    {
        $data = input('get.');

        try{
            validate(ProductValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $where = [];

        /** 搜索条件 */
        if($data && isset($data['key'])){
            if(!empty($data['key']['name'])){
                $where[] = [['name', 'like', '%' . $data['key']['name'] . '%']];
            }
        }

        /** 查询数据总条数 */
        $count = $this->productModel->getNum($where)['data'];

        /** 查询列表 */
        $list = $this->productModel->getList($where, 1, $data['page'], $data['limit'], '*', 'create_time DESC');

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        $this->success_back('ok', $list['data'], $count);
    }

    /** 产品添加 */
    public function product_add_data()
    {
        $data = input('');
        $data['show_img'] = request()->file('show_img');

        try{
            validate(ProductValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $bannerImg = json_decode($data['banner_img'], true);
        unset($data['banner_img']);

        if(empty($bannerImg)){
            $this->error_back('轮播图不能为空');
        }

        /** 添加产品 */
        $data['show_img'] = fileUp($data['show_img'], 'product');
        $flag = $this->productModel->add($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        /** 轮播图 */
        $goodsImg = [];
        foreach($bannerImg as $val){
            $bannerImgArr = [
                'img'        => $val['url'],
                'obj_type'   => 1,
                'obj_id'     => $flag['data'],
                'obj_cate'   => 1,
                'sort'       => $val['sort'],
            ];
            
            $goodsImg[] = $bannerImgArr;
        }

        $imgModel = new Img();

        /** 添加图片 */
        $imgModel->addAll($goodsImg);

        $productSkuModel = new ProductSku();

        $skuIds = explode(',', $data['sku_id']);
        array_pop($skuIds);

        $skuArr = [];
        foreach($skuIds as $val){
            $skuArr[] = [
                'product_id'        => $flag['data'],
                'sku_id'   => $val,
            ];
        }

        /** 添加规格 */
        $productSkuModel->addAll($skuArr);

        $this->success_back('添加成功');
    }

    /** 产品修改 */
    public function product_edit_data()
    {
        $data = input('');
        $data['show_img'] = request()->file('show_img');

        try{
            validate(ProductValidate::class)->scene('edit')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $bannerImg = json_decode($data['banner_img'], true);
        unset($data['banner_img']);

        if(empty($bannerImg)){
            $this->error_back('轮播图不能为空');
        }

        if($data['show_img']){
            $data['show_img'] = fileUp($data['show_img'], 'product');
        }else{
            unset($data['show_img']);
        }

        $flag = $this->productModel->edit($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        /** 轮播图 */
        $goodsImg = [];
        foreach($bannerImg as $val){
            $bannerImgArr = [
                'img'        => $val['url'],
                'obj_type'   => 1,
                'obj_id'     => $data['id'],
                'obj_cate'   => 1,
                'sort'       => $val['sort'],
            ];
            
            $goodsImg[] = $bannerImgArr;
        }

        $imgModel = new Img();

        $imgModel->del(['obj_type' => 1, 'obj_id' => $data['id'], 'obj_cate' => 1]);

        /** 添加图片 */
        $imgModel->addAll($goodsImg);

        $productSkuModel = new ProductSku();

        $skuIds = explode(',', $data['sku_id']);
        array_pop($skuIds);

        $skuArr = [];
        foreach($skuIds as $val){
            $skuArr[] = [
                'product_id'  => $data['id'],
                'sku_id'      => $val,
            ];
        }

        $productSkuModel->del(['product_id' => $data['id']]);

        /** 添加规格 */
        $productSkuModel->addAll($skuArr);

        $this->success_back('修改成功');
    }

    /** 删除产品 */
    public function product_del()
    {
        $data = input('');

        try{
            validate(ProductValidate::class)->scene('show_admin')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $this->productModel::destroy($data['id']);

        if(!$flag){
            $this->error_back($flag['msg']);
        }

        $this->success_back('删除成功');
    }



    /** 渲染规格列表页面 */
    public function sku_list()
    {
        return view();
    }

    /** 渲染规格添加页面 */
    public function sku_add()
    {
        return view();
    }

    /** 规格数据列表 */
    public function sku_data()
    {
        $data = input('get.');

        try{
            validate(SkuValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $skuModel = new Sku();

        /** 查询数据总条数 */
        $count = $skuModel->getNum()['data'];

        /** 查询列表 */
        $list = $skuModel->getList([], 1, $data['page'], $data['limit'], '*', 'id');

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        $this->success_back('ok', $list['data'], $count);
    }

    /** 添加规格 */
    public function sku_add_data()
    {
        $data = input('');

        try{
            validate(SkuValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $skuModel = new Sku();

        $flag = $skuModel->add(['name' => $data['name']]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('添加成功');
    }

    /** 修改规格名称 */
    public function set_sku_name()
    {
        $data = input('');

        try{
            validate(SkuValidate::class)->scene('edit')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $skuModel = new Sku();

        $flag = $skuModel->edit(['id' => $data['id'], $data['field'] => $data['value']]);

        if($flag['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        $this->success_back('编辑成功');
    }

    /** 删除规格 */
    public function sku_del()
    {
        $data = input('');

        try{
            validate(SkuValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $skuModel = new Sku();

        $flag = $skuModel->del(['id' => $data['id']]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('删除成功');
    }



    /** 文件上传 */
    public function img_up(){
        $file = request()->file('file');

        $imgUrl = fileUp($file, 'product');
        $this->success_back('ok', $imgUrl);
    }

    /** 图片删除 */
    public function img_del(){
        $data = input("post.url_img");

        $imgModel = new Img();
        $res = $imgModel->where("img", $data)->delete();

        if(!$res){
            $this->error_back('删除失败');
        }else{
            $this->success_back('删除成功');
        }
    }
}
